package com.codesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.codesandbox.model.ExecuteCodeRequest;
import com.codesandbox.model.ExecuteCodeResponse;
import com.codesandbox.model.ExecuteMessage;
import com.codesandbox.model.JudgeInfo;
import com.codesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
public abstract class JavaCodeSandboxTemplate implements CodeSandbox{
    private static final String GLOBAL_CODE_DIR_NAME="tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME="Main.java";
    private static final long TIME_OUT=10000L;

    public File saveFile(String code){
        //怎么执行代码-》首先，将code转换为一个java文件-》然后，编译java文件-》最后，执行java文件
        //创建存储java文件的文件夹
        //获取工作目录
        String userDir = System.getProperty("user.dir");
        String globalCodePathName=userDir+ File.separator+GLOBAL_CODE_DIR_NAME;
        //判断这个文件夹是否存在，不存在则创建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        //将每个用户的代码分开放
        String userCodeParentPath=globalCodePathName+File.separator+ UUID.randomUUID();
        String userCodePath=userCodeParentPath+File.separator+GLOBAL_JAVA_CLASS_NAME;
        //将code写成java文件
        File Javafile = FileUtil.writeUtf8String(code, userCodePath);
        return  Javafile;
    }
    public ExecuteMessage compileFile(File javaFile){
        //编译代码
        //构造编译命令
        String compiledCmd = String.format("javac -encoding utf-8 %s",javaFile.getAbsoluteFile());
        //执行编译命令
        try {
            Process compileProcess = Runtime.getRuntime().exec(compiledCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);
            if(executeMessage.getExitValue()!=0){
//                throw new RuntimeException("编译错误");
                log.error("编译错误，错误信息为:{}",executeMessage.getErrorMessage());
            }
            return executeMessage;
        } catch (Exception e) {
//            return getErrorResponse(e);
            throw  new RuntimeException(e);
        }
    }
    public List<ExecuteMessage>runFile(File userCodeFile,List<String>inputList){
        String userCodeParentPath=userCodeFile.getParentFile().getAbsolutePath();
        List<ExecuteMessage>executeMessageList=new ArrayList<>();
        for(String inputArgs:inputList){
//            String runCmd=String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s",userCodeParentPath,inputArgs);
            String runCmd=String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s",userCodeParentPath,inputArgs);
            try {
                Process runProcess=Runtime.getRuntime().exec(runCmd);
                //超时控制
                new Thread(()->{
                    try {
                        Thread.sleep(TIME_OUT);
                        System.out.println("超时了，中断");
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
//                ExecuteMessage executeMessage = ProcessUtils.runInteractProcessAndGetMessage(runProcess,inputArgs);
                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);
            } catch (Exception e) {
                throw new RuntimeException("执行错误",e);
            }
        }
        return executeMessageList;
    }
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> messageList){
        //构造返回结果
        ExecuteCodeResponse executeCodeResponse=new ExecuteCodeResponse();
        //取最大值-》判断是否超时
        long maxTime=0;
        //存结果信息
        List<String> outputList=new ArrayList<>();
        for (ExecuteMessage executeMessage : messageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(errorMessage)){
                executeCodeResponse.setMessage(errorMessage);
                //用户提交代码执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            //存正常信息
            outputList.add(executeMessage.getMessage());
            //找最大的时间
            Long time=executeMessage.getTime();
            if(time!=null){
                maxTime=Math.max(maxTime,time);
            }
        }
        //正常运行完成
        Integer status = executeCodeResponse.getStatus();
        if(outputList.size()==messageList.size()){
            executeCodeResponse.setStatus(1);
            if(status!=null&&status.equals(3)){
                executeCodeResponse.setStatus(3);
            }
            executeCodeResponse.setMessage("");
        }
        executeCodeResponse.setOuputList(outputList);
        JudgeInfo judgeInfo=new JudgeInfo();
        judgeInfo.setTime(maxTime);
        judgeInfo.setMemory(messageList.get(0).getMemory());
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }
    public boolean clearFile(File javaFile){
        if(javaFile.getParentFile()!=null){
            //直接删除对应的文件夹
            boolean del=FileUtil.del(javaFile.getParentFile().getAbsoluteFile());
            System.out.println("删除文件"+(del?"成功":"失败"));
            return del;
        }
        return true;
    }
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String language = executeCodeRequest.getLanguage();
        String code = executeCodeRequest.getCode();
        //保存文件
        File javaFile = saveFile(code);
        String userCodeParentPath=javaFile.getParentFile().getAbsolutePath();
        //编译文件
        ExecuteMessage  compileFileExecuteMessage = compileFile(javaFile);
        //运行代码
        List<ExecuteMessage> messageList = runFile(javaFile, inputList);
        //获取响应结果
        ExecuteCodeResponse executeCodeResponse = getOutputResponse(messageList);
        //5.文件清理
        clearFile(javaFile);
        return executeCodeResponse;
    }
    /**
     * 获取错误响应
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e){
        ExecuteCodeResponse executeCodeResponse=new ExecuteCodeResponse();
        executeCodeResponse.setOuputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //表示代码沙箱错误（可能是编译错误）
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}
